package org.hcf.utils;

import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

/**
 * @author changfu.he
 * @email changfu.he@weimob.com
 * @date 2021/9/29
 */
public class FuncUtils {
    private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
    private static final Pattern SET_PATTERN = Pattern.compile("^set[A-Z].*");
    private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");

    /**
     * 获取func的 字段名
     * @param f
     * @param <F> SeriFunc 或者 SeriSupplier 都可以
     * @return
     */
    public static <F> String mapFieldName(F f){
        String methName = mapFuncName(f);
        if (
                GET_PATTERN.matcher(methName).matches()
                || SET_PATTERN.matcher(methName).matches()
        ) {
            methName = methName.substring(3);

        } else if (IS_PATTERN.matcher(methName).matches()) {
            methName = methName.substring(2);
        }
        return Introspector.decapitalize(methName);

    }

    public static <F> String mapFuncName(F f){
        try {
            Method method = f.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(f);
            String methName = serializedLambda.getImplMethodName();
            return methName;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }


}
